#include <stdio.h>
#include "common_list.h"


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val) {
    struct ListNode *tmp = (struct ListNode*)malloc(sizeof(*head));
    tmp->next = head;

    struct ListNode *ptr = tmp;
    while(ptr && ptr->next) {
        if (ptr->next->val == val) {
            if (ptr->next->next) {
                struct ListNode *delete = ptr->next;
                ptr->next = ptr->next->next;
                free(delete);
            } else {
                free(ptr->next);
                ptr->next = NULL;
            }
        } else {
            ptr = ptr->next;
        }
    }

    return tmp->next;
}

int main(void)
{
    printf("#203. 移除链表元素\n");
    int nums[] = {35,5,5,5,5};
    struct ListNode *head = generate_list_val(sizeof(nums)/sizeof(int), nums);
    print_list(head);
    head = removeElements(head, 5);
    print_list(head);

    return 0;
}